import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Tools,ActionSheet } from 'weaver-mobile';
import {openWorkFlow,resetNavBar} from '../../util/pulic-func';
import { withRouter } from 'react-router-dom';
import {getUrlParam} from '../../util/common';

const getLabel = Tools.getLabel;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@inject ('walletStore','baseStore')
@observer
class ToWalletCloud extends React.Component {
    constructor(props){
        super(props);
        const {location:{search}} = this.props;
        this.urlParam = getUrlParam(search);
    }

    componentWillMount(){
        const { baseStore } = this.props;
        const { getEquipmentFn } = baseStore;
        getEquipmentFn();
    }

    componentDidMount() {
        const { baseStore } = this.props;
        const { invoiceCloudInfo,getInvoiceCloudToken } = baseStore;

        if(invoiceCloudInfo.invoiceCloud == undefined){
            getInvoiceCloudToken({});
        }

        window.addEventListener('message',this.receiver,false);
    }

    componentWillUnmount(){
        ActionSheet.close();
        window.removeEventListener('message',this.receiver,false)
    }

    render() {
        const {walletStore,baseStore} = this.props;
        // const {cloudInvoiceId} = walletStore;
        const { getInvoiceCloudUrl } = baseStore; 

        return (
            <div style={{height:'100%'}}>
                {this.urlParam.frame === 'ON_PREVIEW' && <iframe className='ec-iframe' src={getInvoiceCloudUrl('wallet',2,{id:this.urlParam.cloudInvoiceId})} style={{width:'100%',height:'100%',border:'0'}} id={"myIframe"} ></iframe>}
                {this.urlParam.frame === 'controlEmTopNav' && <iframe className='ec-iframe' src={getInvoiceCloudUrl('wallet',1)} style={{width:'100%',height:'100%',border:'0'}} id={"myIframe"} ></iframe>}

            </div>
                

        )
    }

    receiver = (event) =>{
        const {invoiceCloudInfo} = this.props.baseStore;
        if (invoiceCloudInfo.jsUrl != event.origin) return;
        let returnData = event.data;
        console.log('toWalletCloud------returnData',returnData);

        const {walletStore} = this.props;
        const {setStateParams} = walletStore;

        switch(returnData.type){
            
            case 'ON_WILL_LOAD' :
                setStateParams({onRowSelect:[]});
                // setLoading(true);
                break;
            case 'ON_LOADED' :
                // setLoading(false)
                break;  
            case 'ERROR' :
                if(returnData.ret == '-2'){
                    this.sendToken();
                }
                break;
            case 'PREVIEW_ACTION':
                if(returnData.action == 'CHARGE'){
                    this.props.history.push(`/remember?invoiceIds=${returnData.invoices[0].oaid}`)
                }else if(returnData.action == 'EXPENSE'){
                    const { getInvoiceCreatWorkflow } = walletStore;
                    getInvoiceCreatWorkflow({
                        invoiceIds:returnData.invoices[0].oaid
                    },(value)=>{
                        const { invoiceCreatWorkflow } = walletStore;
                        const {workflowSelect} = value

                        let allMonth = workflowSelect;
                        ActionSheet.showActionSheetWithOptions({
                            options: allMonth,
                            cancelButtonIndex: allMonth.length - 1,
                            // destructiveButtonIndex: BUTTONS.length - 2,
                            // title: '请选择月份',
                            // message: '请选择月份',
                            maskClosable: true,
                            'data-seed': 'logId',
                            wrapProps,
                        },  
                        (buttonIndex) => {
                            if(buttonIndex != allMonth.length - 1){
                                let params = {
                                    workflowId:workflowSelect[buttonIndex].id,
                                    id:returnData.invoices[0].oaid
                                }

                                invoiceCreatWorkflow(params,(value)=>{
                                    openWorkFlow('view',value.requestId,()=>{
                                        // let _key = this.state._key == '0' ? '1' : '0';
                                        // this.setState({
                                        //     _key:_key
                                        // })
                                    });
                                })
                            }
                                
                        });    
                    });

                    
                }
                
                break;                
            default :
                break;                           
        }


        
    }

    //发送 token
    sendToken = () =>{
        const {baseStore} = this.props;
        const {getInvoiceCloudToken} = baseStore;
        getInvoiceCloudToken({tokenUnusual:1},()=>{
            let childFrame = document.getElementById("myIframe");
            let url = baseStore.invoiceCloudInfo.jsUrl;
            childFrame.contentWindow.postMessage({
                type: 'UPDATE_TOKEN',
                token:baseStore.invoiceCloudInfo.token
            }, url); 
        })

    }    




}

export default ToWalletCloud;